/**
 * Copyright &copy; 2012-2014 <a href="https://its111.com">Its111</a> All rights reserved.
 */
package com.hachismart.interceptor;

import com.google.gson.reflect.TypeToken;
import com.hachismart.common.ip.IPUtils;
import com.hachismart.common.redis.RedisHashUtil;
import com.pujitech.common.utils.JsonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author abbott
 */
@Configuration
public class IpInterceptor implements HandlerInterceptor {

    private final Log log = LogFactory.getLog(this.getClass());
    @Autowired
    RedisHashUtil redisHashUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        String blackListStr = redisHashUtil.get("ipList", "blackList");
        String whiteListStr = redisHashUtil.get("ipList", "whiteList");

        List<String> blackList = JsonUtils.json2Objs(blackListStr, new TypeToken<List<String>>() {
        });

        List<String> whiteList = JsonUtils.json2Objs(whiteListStr, new TypeToken<List<String>>() {
        });


        String ipAddress = IPUtils.getIpAddress(request);
        //如果在黑名单中直接禁止访问
        if (CollectionUtils.isNotEmpty(blackList)) {
            if (blackList.contains(ipAddress)) {
                return false;
            }
        }
            //如果不在白名单中 禁止访问
        if (CollectionUtils.isNotEmpty(whiteList)) {
            if (!blackList.contains(ipAddress)) {
                return false;
            }
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {


    }

}
